package com.gemini.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        //和登录注册相关的应该放行
        String requestURL = httpServletRequest.getRequestURL().toString();
        String[] urls={"/login.jsp","/register.jsp","/css","/img","/login","/register","/checkCode"};
        for (String url:urls){
            if(requestURL.contains(url)){
                chain.doFilter(request,response);
                return;
            }
        }
        String username = (String)httpServletRequest.getSession().getAttribute("username");
        if(username==null){
            System.out.println("被拦截");
            request.setAttribute("login_msg","您尚未登录");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }else {
            chain.doFilter(request,response);
        }
    }
}
